package com.sikadwafastdaisfondturbo.pretloan.utils.http

import android.os.Handler
import android.os.Looper
import com.sikadwa.syc.http.HttpRequestBuilder
import com.sikadwafastdaisfondturbo.pretloan.utils.config.Configs
import com.sikadwafastdaisfondturbo.pretloan.utils.event.track.TrackEventManager
import com.sikadwafastdaisfondturbo.pretloan.utils.log.HHLog
import com.sikadwafastdaisfondturbo.pretloan.utils.log.JsonFormat
import org.json.JSONObject
import java.io.File


/**
 * Sikadwa
 *
 * @Author wwdeng
 * @CreateTime: 2024/5/20 18:04
 * @Annotation：
 */
class OkHttpLoaderV3 : IHttpLoader {

    companion object {
        private const val MAX_RETRIES = 2 // 最大重试次数（不包括首次请求）
    }

    override fun get(url: String, callback: IHttpCallback) {
        executeRequest(url, "GET", null, callback, false, null)
    }

    override fun post(url: String, params: JSONObject, callback: IHttpCallback) {
        executeRequest(url, "POST", params, callback, false, null)
    }

    override fun uploadFile(url: String, file: File, callback: IHttpCallback) {
        executeRequest(url, "POST", null, callback, true, file)
    }

    private fun executeRequest(url: String, method: String, params: JSONObject?, callback: IHttpCallback, isFileUpload: Boolean, file: File?) {
        val request = GlobalNetworkManager.RetryRequest(
            url = url,
            method = method,
            params = params,
            callback = callback,
            isFileUpload = isFileUpload,
            file = file
        )

        when {
            isFileUpload && file != null -> executeFileUpload(request)
            method == "GET" -> executeGet(request)
            else -> executePost(request)
        }
    }

    /**
     * get
     */
    private fun executeGet(request: GlobalNetworkManager.RetryRequest) {
        HHLog.i("GET START: ${request.url}, retryCount: ${request.retryCount}")

        HttpRequestBuilder()
            .url(request.url)
            .method("GET")
            .addHeader("product", Configs.AppName)
            .addHeader("appid", Configs.AppName)
            .timeouts(20000, 20000)
            .execute(createCallback(request))
    }

    /**
     * post
     */
    private fun executePost(request: GlobalNetworkManager.RetryRequest) {
        val aesParams = AESCryptUtil.encryptDefault(request.params?.toString() ?: "")

        HHLog.i("POST START: ${request.url}, retryCount: ${request.retryCount}")
        HHLog.e("HttpUrl：  ${request.url}")
        HHLog.e("HttpParams： ${request.params}")
        HHLog.e("HttpParams AES：  $aesParams")

        HttpRequestBuilder()
            .url(request.url)
            .method("POST")
            .addHeader("product", Configs.AppName)
            .addHeader("appid", Configs.AppName)
            .body(aesParams)
            .timeouts(20000, 20000)
            .execute(createCallback(request))
    }

    /**
     * post upload file
     */
    private fun executeFileUpload(request: GlobalNetworkManager.RetryRequest) {
        request.file?.let { file ->
            HHLog.i("FileUpload START: ${request.url}, retryCount: ${request.retryCount}")

            HttpRequestBuilder()
                .url(request.url)
                .method("POST")
                .addHeader("product", Configs.AppName)
                .addHeader("appid", Configs.AppName)
                .timeouts(20000, 20000)
                .uploadFile(file.path, createCallback(request))
        }
    }

    private fun createCallback(request: GlobalNetworkManager.RetryRequest): HttpRequestBuilder.Callback {
        return object : HttpRequestBuilder.Callback {
            override fun onSuccess(response: String) {
                handleSuccess(response, request.isFileUpload,request.callback)
            }

            override fun onFailure(code: Int, msg: String?) {
                handleFailure(code, msg, request)
            }

            override fun onFinished() {
                request.callback.onRequestFinish()
            }
        }
    }

    private fun handleSuccess(response: String,isFileUpload: Boolean, callback: IHttpCallback) {
        try {
            if (isFileUpload){//上传文件不需要加解密
                if (response.isEmpty()){
                    val errorObj = JSONObject()
                    errorObj.put("errorCode", -1)
                    errorObj.put("errorMsg", "http request error")
                    callback.onRequestError(errorObj)
                } else {
                    Thread {
                        HHLog.i("data：" + JsonFormat.format(response))
                    }.start()
                    val data = JSONObject(response)
                    callback.onRequestSuccess(data)
                }
            } else {//普通请求需要解密
                val result = AESCryptUtil.decryptDefault(response)
                if (result.isNotEmpty()) {
                    Thread {
                        HHLog.i("data：" + JsonFormat.format(result))
                    }.start()
                    val jsonResult = JSONObject(result)
                    Handler(Looper.getMainLooper()).post {
                        callback.onRequestSuccess(jsonResult)
                    }
                } else {
                    val errorObj = JSONObject().apply {
                        put("errorCode", -1)
                        put("errorMsg", "The response data is empty")
                    }
                    Handler(Looper.getMainLooper()).post {
                        callback.onRequestError(errorObj)
                    }
                }
            }
        } catch (e: Exception) {
            val errorObj = JSONObject().apply {
                put("errorCode", -1)
                put("errorMsg", "Data parsing failed: ${e.message}")
            }
            Handler(Looper.getMainLooper()).post {
                callback.onRequestError(errorObj)
            }
        }
    }

    private fun handleFailure(code: Int, msg: String?, request: GlobalNetworkManager.RetryRequest) {
        HHLog.e("Request failed: ${request.url}, code: $code, msg: $msg, retryCount: ${request.retryCount}")

        // 判断是否应该重试
        if (shouldRetry(code) && request.retryCount < MAX_RETRIES) {
            // 交给全局管理器处理
            GlobalNetworkManager.handleNetworkError(code, msg, request)
        } else {
            // 超过重试次数或不可重试的错误，直接回调
            val errorObj = JSONObject().apply {
                put("errorCode", code)
                put("errorMsg", msg ?: "Request failed")
            }
            Handler(Looper.getMainLooper()).post {
                request.callback.onRequestError(errorObj)
            }

            // 如果是最终失败且是全局错误，显示提示
            if (shouldRetry(code)) {
                GlobalNetworkManager.handleNetworkError(code, msg, request)
            }
        }
    }

    private fun shouldRetry(errorCode: Int): Boolean {
        return errorCode == -1 || errorCode == 408 || errorCode in 500..599
    }

    /**
     * 添加埋点
     */
    override fun addEvent(eventName: String, remark: String?) {
        var eventType = eventName.uppercase()//转大写
        if(!eventType.startsWith("SIKADWA_")){
            eventType = "SIKADWA_$eventType"
        }
        TrackEventManager.trackEvent(eventType,remark)
    }
}
